<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>vue钩子函数-路由导航/生命周期钩子- | 雨落</title>
  <meta name="description" content="vue的钩子函数（路由导航，keep-alive，生命周期钩子）vue-router导航守卫 场景：如登录权限控制，满足条件才能进入导航，否则取消跳转，并跳转到登陆页面全局路由守卫： router.beforeEach 全局前置路由守卫，在进入路由前触发 router.beforeResolve  全局解析守卫(2.5.0+) 在beforeRouteEnter调用之后调用 router.afte">
<meta property="og:type" content="article">
<meta property="og:title" content="vue钩子函数-路由导航&#x2F;生命周期钩子-">
<meta property="og:url" content="https://gitee.com/Yu-Luoboke/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/index.html">
<meta property="og:site_name" content="雨落">
<meta property="og:description" content="vue的钩子函数（路由导航，keep-alive，生命周期钩子）vue-router导航守卫 场景：如登录权限控制，满足条件才能进入导航，否则取消跳转，并跳转到登陆页面全局路由守卫： router.beforeEach 全局前置路由守卫，在进入路由前触发 router.beforeResolve  全局解析守卫(2.5.0+) 在beforeRouteEnter调用之后调用 router.afte">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-01-18T02:36:17.000Z">
<meta property="article:modified_time" content="2021-10-30T06:41:16.278Z">
<meta property="article:author" content="lianghongming">
<meta name="twitter:card" content="summary">
  <!-- Canonical links -->
  <link rel="canonical" href="https://gitee.com/Yu-Luoboke/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/index.html">
  
    <link rel="alternate" href="/atom.xml" title="雨落" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/blog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 5.2.0"></head>


<body class="main-center" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="http://yu-luoboke.gitee.io/blog" target="_blank">
          <img class="img-circle img-rotate" src="/blog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">雨落</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">前端开发-奋斗青年</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> GuangZhou, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/blog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="http://yu-luoboke.gitee.io/blog" target="_blank" title="Github" ><i class="icon icon-github"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Git/">Git</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/HTML-CSS/">HTML + CSS</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/JVM%EF%BC%88Java%E8%99%9A%E6%8B%9F%E6%9C%BA%EF%BC%89-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95/">JVM（Java虚拟机）-垃圾回收算法</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Node/">Node</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Project/">Project</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/React/">React</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/SVN/">SVN</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/Vue-typescript/">Vue-typescript</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/gitee/">gitee</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/iOS/">iOS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/js/">js</a><span class="category-list-count">12</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/vue/">vue</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/web-serve%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E6%9C%8D%E5%8A%A1%E5%99%A8/">web serve静态资源服务器</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/webpack/">webpack</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E5%89%8D%E7%AB%AF%E8%87%AA%E5%8A%A8%E5%8C%96/">前端自动化</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E5%B0%8F%E7%A8%8B%E5%BA%8F/">小程序</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E7%A7%BB%E5%8A%A8%E7%AB%AF/">移动端</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E7%BB%8F%E9%AA%8C/">经验</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a><span class="category-list-count">4</span></li></ul>
    </div>
  </div>


    
      

    
      
    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2024/04/">四月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2023/11/">十一月 2023</a><span class="archive-list-count">8</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2023/09/">九月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/12/">十二月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/08/">八月 2022</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/07/">七月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/06/">六月 2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/04/">四月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/01/">一月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/12/">十二月 2021</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/11/">十一月 2021</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/10/">十月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/04/">四月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/03/">三月 2021</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/02/">二月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/01/">一月 2021</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/12/">十二月 2020</a><span class="archive-list-count">15</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/HTML-CSS/">HTML + CSS</a>
              </p>
              <p class="item-title">
                <a href="/blog/2024/04/15/%E6%8B%96%E5%8A%A8%E5%92%8C%E7%82%B9%E5%87%BB%E5%BC%B9%E7%AA%97/" class="title">拖动和点击弹窗</a>
              </p>
              <p class="item-date">
                <time datetime="2024-04-15T12:22:06.000Z" itemprop="datePublished">2024-04-15</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/html%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">html面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:58:27.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/css%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">css面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:57:17.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/js%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">js面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:37:30.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/blog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
              </p>
              <p class="item-title">
                <a href="/blog/2023/11/29/%E9%9D%A2%E8%AF%95%E9%A2%98/" class="title">面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2023-11-29T15:29:49.000Z" itemprop="datePublished">2023-11-29</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-vue钩子函数-路由导航-生命周期钩子" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      vue钩子函数-路由导航/生命周期钩子-
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/blog/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/" class="article-date">
	  <time datetime="2021-01-18T02:36:17.000Z" itemprop="datePublished">2021-01-18</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/blog/categories/vue/">vue</a>
  </span>

        

        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/blog/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h3 id="vue的钩子函数（路由导航，keep-alive，生命周期钩子）"><a href="#vue的钩子函数（路由导航，keep-alive，生命周期钩子）" class="headerlink" title="vue的钩子函数（路由导航，keep-alive，生命周期钩子）"></a>vue的钩子函数（路由导航，keep-alive，生命周期钩子）</h3><h4 id="vue-router导航守卫"><a href="#vue-router导航守卫" class="headerlink" title="vue-router导航守卫"></a>vue-router导航守卫</h4><ul>
<li>场景：如登录权限控制，满足条件才能进入导航，否则取消跳转，并跳转到登陆页面<h4 id="全局路由守卫："><a href="#全局路由守卫：" class="headerlink" title="全局路由守卫："></a>全局路由守卫：</h4><ul>
<li>router.beforeEach 全局前置路由守卫，在进入路由前触发</li>
<li>router.beforeResolve  全局解析守卫(2.5.0+) 在beforeRouteEnter调用之后调用</li>
<li>router.afterEach 全局后置钩子 进入路由之后</li>
</ul>
</li>
<li>使用：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可以卸载main.js文件或者路由index.js文件</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> Router(&#123;……&#125;)</span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to,<span class="keyword">from</span>,next</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(to.path === <span class="string">&#x27;home&#x27;</span> &amp;&amp; <span class="keyword">from</span>.path === <span class="string">&#x27;login&#x27;</span>) <span class="comment">// to：即将跳转的目标路由（去哪里） from：是从那个路由跳转进来的（从哪里来）</span></span><br><span class="line">    next() <span class="comment">// 进入下一个路由，必须调用next(),否则不能进入路由，导致页面空白</span></span><br><span class="line">    next(<span class="string">&#x27;/&#x27;</span>)</span><br><span class="line">    nett(&#123;<span class="attr">path</span>:<span class="string">&#x27;/home&#x27;</span>&#125;) <span class="comment">// 跳转到指定的路由</span></span><br><span class="line">    next(&#123;<span class="attr">name</span>:<span class="string">&#x27;home&#x27;</span>&#125;)</span><br><span class="line">    next(<span class="literal">false</span>) <span class="comment">// 中断路由</span></span><br><span class="line">&#125;)</span><br><span class="line">router.beforeResolve(<span class="function">(<span class="params">to,<span class="keyword">from</span>,next</span>)=&gt;</span>&#123;</span><br><span class="line">    next()</span><br><span class="line">&#125;)</span><br><span class="line">router.afterEach(<span class="function">(<span class="params">to,<span class="keyword">from</span></span>)=&gt;</span>&#123; <span class="comment">// 无next()函数</span></span><br><span class="line">    next()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="路由独享守卫（只在某个路由生效）"><a href="#路由独享守卫（只在某个路由生效）" class="headerlink" title="路由独享守卫（只在某个路由生效）"></a>路由独享守卫（只在某个路由生效）</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> Router(&#123;</span><br><span class="line">    routes:[&#123;</span><br><span class="line">        path: <span class="string">&#x27;home&#x27;</span>,</span><br><span class="line">        name: <span class="string">&#x27;homt&#x27;</span>,</span><br><span class="line">        component: Home,</span><br><span class="line">        beforeEach:<span class="function">(<span class="params">to,<span class="keyword">from</span>,next</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="comment">// 调用顺序在全局守卫的后面，并不会被全局守卫覆盖</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;]</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="组件内的守卫"><a href="#组件内的守卫" class="headerlink" title="组件内的守卫"></a>组件内的守卫</h4></li>
<li>beforeRouteEnter 进入路由前（进入组件前）</li>
<li>beforeRouteUpdate(2.2) 路由复用一个组件时</li>
<li>beforeRouteLeave 离开当前路由时（离开当前组件前）</li>
<li>文档中的介绍<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">beforeRouterEnter</span>(<span class="params">to,<span class="keyword">from</span>,next</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 在路由独享守卫后调用，组件实例还没被创建，不能获取组件实例this</span></span><br><span class="line">    <span class="comment">// 解决方法：通过传递一个回调函数给next()</span></span><br><span class="line">    next(<span class="function"><span class="params">vm</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 通过vm访问组件实例this , 在created生命周期后，mounted生命周期前调用</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="title">beforeRouterUpdate</span>(<span class="params">to,<span class="keyword">from</span>,next</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 在当前路由改变，但是该组件被复用时调用 可以访问组件实例 `this`</span></span><br><span class="line">    <span class="comment">// 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候</span></span><br><span class="line">    <span class="comment">// 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="title">beforeRouterLeave</span>(<span class="params">to, <span class="keyword">from</span>, next</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 导航离开组件时调用，可以访问组件实例this</span></span><br><span class="line">    <span class="comment">// 应用场景：如离开组件前某些操作还没完成，禁止用户离开当前组件/销毁定时器等</span></span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">        next()</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        next(<span class="literal">false</span>) <span class="comment">// 禁止用户离开</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="路由钩子函数的错误捕获"><a href="#路由钩子函数的错误捕获" class="headerlink" title="路由钩子函数的错误捕获"></a>路由钩子函数的错误捕获</h4></li>
<li>如果我们在全局守卫/路由独享守卫/组件路由守卫的钩子函数中有错误，可以这样捕获：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">router.onError(<span class="function"><span class="params">callback</span> =&gt;</span> &#123; </span><br><span class="line">    <span class="comment">// 2.4.0新增 并不常用，了解一下就可以了 </span></span><br><span class="line">    <span class="built_in">console</span>.log(callback, <span class="string">&#x27;callback&#x27;</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="错误提示：Maximum-call-stack-exceeded（堆栈溢出，即死循环）常现场景：验证用户是否已登录"><a href="#错误提示：Maximum-call-stack-exceeded（堆栈溢出，即死循环）常现场景：验证用户是否已登录" class="headerlink" title="错误提示：Maximum call stack exceeded（堆栈溢出，即死循环）常现场景：验证用户是否已登录"></a>错误提示：Maximum call stack exceeded（堆栈溢出，即死循环）常现场景：验证用户是否已登录</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 堆栈溢出</span></span><br><span class="line"> router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(已登录)&#123; <span class="comment">// 这样判断貌似没有问题，但是，当我们首次进来，肯定是未登录的，所以导致一直都是走else，最后造成了堆栈溢出,导致页面空白</span></span><br><span class="line">         next()  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          next(&#123; <span class="attr">name</span>: <span class="string">&#x27;login&#x27;</span> &#125;)&#125;</span><br><span class="line">    &#125;)</span><br><span class="line"><span class="comment">// 修改</span></span><br><span class="line">router.beforeEach(<span class="function">(<span class="params">to, <span class="keyword">from</span>, next</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="literal">true</span>)&#123; <span class="comment">// 需要登录权限</span></span><br><span class="line">    <span class="keyword">if</span>(已登录)&#123; <span class="comment">// 这样判断貌似没有问题，但是，当我们首次进来，肯定是未登录的，所以导致一直都是走else，最后造成了堆栈溢出,导致页面空白</span></span><br><span class="line">        next()  </span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        next(&#123; <span class="attr">name</span>: <span class="string">&#x27;login&#x27;</span> &#125;)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123; next() &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="完整的导航解析流程"><a href="#完整的导航解析流程" class="headerlink" title="完整的导航解析流程"></a>完整的导航解析流程</h4></li>
<li>导航被触发，进入其它路由</li>
<li>在失活的组件调用 beforeRouterLeave 守卫 (组件路由)</li>
<li>调用全局的 boforeEach 守卫</li>
<li>在重用的组件里调用 beforeRouterUpdate 守卫(2.2+)</li>
<li>在路由配置里调用 beforeEach (触发路由独享守卫)</li>
<li>解析异步路由组件（component:()=&gt;import(‘xxx/xxx.vue’)）</li>
<li>在被激活的组件里面调用 beforeRouterEnter (组件路由)</li>
<li>调用全局的 beforeResolve 守卫(2.5+)</li>
<li>导航被确认</li>
<li>调用全局的 afterEach 钩子</li>
<li>触发 dom 更新</li>
<li>调用 beforeRouteEnter 守卫中传给 next 的回调函数，创建好的组件实例会作为回调函数的参数传入</li>
</ul>
<h4 id="keep-alive缓存组件"><a href="#keep-alive缓存组件" class="headerlink" title="keep-alive缓存组件"></a>keep-alive缓存组件</h4><ul>
<li>keep-alive缓存组件中多出两个生命周期的钩子：activated（进入缓存组件都会触发）和deactivated</li>
<li>activated的调用时机：第一次进入缓存路由/组件，在mounted后面，beforeRouterEnter守卫传给next的回调函数前调用</li>
<li>因为组件被缓存，再次进入缓存组件时，beforeCreate,created,beforeMounted,mounted 都不会被触发</li>
<li>deactivated：组件被停用或者离开路由时调用</li>
<li>因为组件会被缓存起来，不会被销毁，所以不会执行beforeDestroy和destroy</li>
<li>离开路由一次触发：beforeRouteLeave ，beforeEach ，afterEach ，deactivated </li>
<li>使用：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;keep-alive include = <span class="string">&#x27;home&#x27;</span>&gt; <span class="comment">// Home组件中必须设置name属性include才会生效，路由中设置的name属性不会生效</span></span><br><span class="line">    &lt;router-view /&gt;</span><br><span class="line">&lt;/keep-alive&gt;</span><br><span class="line">&lt;keep-alive exclude = <span class="string">&#x27;home&#x27;</span>&gt; <span class="comment">// 不缓存home组件，同样需要在组件中设置name属性</span></span><br><span class="line">    &lt;router-view /&gt;</span><br><span class="line">&lt;/keep-alive&gt;</span><br><span class="line">&lt;keep-alive include = <span class="string">&#x27;home&#x27;</span> exclude = <span class="string">&#x27;home&#x27;</span>&gt; <span class="comment">// 两者同时存在，include不会生效，只有exclude生效</span></span><br><span class="line">    &lt;router-view /&gt;</span><br><span class="line">&lt;/keep-alive&gt;</span><br></pre></td></tr></table></figure>
<h3 id="触发钩子的完整顺序"><a href="#触发钩子的完整顺序" class="headerlink" title="触发钩子的完整顺序"></a>触发钩子的完整顺序</h3></li>
<li>将路由导航，keep-alive，组件生命周期三者结合起来，假设从a组件离开，第一次进入b组件<ul>
<li>beforeRouteLeave:路由组件的组件离开路由前钩子，可取消路由离开(next(false))。</li>
<li>beforeEach: 路由全局前置守卫，可用于登录验证、全局路由loading等。</li>
<li>beforeEnter: 路由独享守卫</li>
<li>beforeRouteEnter: 路由组件的组件进入路由前钩子。</li>
<li>beforeResolve:路由全局解析守卫</li>
<li>afterEach:路由全局后置钩子</li>
<li>beforeCreate:组件生命周期，不能访问this。</li>
<li>created:组件生命周期，vue实例创建完成，data和motheds初始化完成，可以访问this，不能访问dom。</li>
<li>执行beforeRouteEnter回调函数next</li>
<li>beforeMount:组件生命周期 生成模板字符串，渲染为虚拟dom</li>
<li>deactivated: 离开缓存组件a，或者触发a的beforeDestroy和destroyed组件销毁钩子。</li>
<li>mounted:访问/操作dom。</li>
<li>activated:进入缓存组件，进入a的嵌套子组件(如果有的话)。</li>
</ul>
</li>
</ul>

      
    </div>
    <div class="article-footer">
      <!-- <blockquote class="mt-2x"> -->
  <!-- <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/Yu-Luoboke/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/" title="vue钩子函数-路由导航/生命周期钩子-" target="_blank" rel="external">https://gitee.com/Yu-Luoboke/2021/01/18/vue%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0-%E8%B7%AF%E7%94%B1%E5%AF%BC%E8%88%AA-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul> -->
<!-- </blockquote> -->


<!-- <div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="http://yu-luoboke.gitee.io/blog" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/blog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="http://yu-luoboke.gitee.io/blog" target="_blank"><span class="text-dark">雨落</span><small class="ml-1x">前端开发-奋斗青年</small></a></h3>
        <div>前端经验总结。</div>
      </div>
    </figure>
  </div>
</div> -->


    </div>
  </article>
  
    

  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/blog/2021/01/21/commonJS%E6%A8%A1%E5%9D%97-es6%E6%A8%A1%E5%9D%97/" title="commonJS模块-es6模块"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/blog/2021/01/12/vue%E9%85%8D%E7%BD%AE%E8%B7%A8%E5%9F%9F%E9%81%87%E5%88%B0%E7%9A%84bug/" title="vue配置跨域遇到的bug"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  
  <div class="bar-right">
    
  </div>
  </div>
</nav>
  


</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="http://yu-luoboke.gitee.io/blog" target="_blank" title="Github" ><i class="icon icon-github"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2024 lianghongming
        
        <div class="publishby">
        	Theme by <a href="https://gitee.com/Yu-Luoboke/blog" target="_blank"> blog </a>base on <a href="https://gitee.com/Yu-Luoboke/blog" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/blog/js/plugin.min.js"></script>


<script src="/blog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/blog/',
        CONTENT_URL: '/blog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/blog/js/insight.js"></script>






   









</body>
</html>